public without sharing class BloodApplicationController {
    public String backId {get; private set;} 
    public String msg {get; private set;} 
    public Boolean isErr {get; private set;} 
    public String dataJson {get; private set;} 
    public String saveJson {get;  set;} 
    public Boolean isSuccess {get ; private set;}
    private  Map<String,String> productMap ;
    private Boolean isNew ;
    private BloodSugarOrder__c bos ;
    public class ControllerException extends Exception {}
    private Map<String,DataUtil.SObjectBean>   stageObjectMap ;
    public String oppId {get;private set;}
    public  Boolean isFromOpp {get;private set;}

    public BloodApplicationController() {
         backId = System.currentPageReference().getParameters().get('id');
         isNew = false;
        productMap = new Map<String ,String>();
        productMap.put('100100100001','110220600001');
        productMap.put('100100100002','110220600002');
        stageObjectMap = new  Map<String,DataUtil.SObjectBean>();

    }

    
    public void setNil(){
        dataJson = '[]';
        saveJson = '[]';
    }
    private void setErr(String message){
        isErr  =true;
        throw new ControllerException(message);
    }


    public void init(){

        try {

             bos = null ; 
            if(backId == null)setErr('页面打开错误');

             Opportunity opp = null;

             Contract__c  con  = null;
            if( Id.valueOf(backId).getSObjectType() == BloodSugarOrder__c.SObjectType ){//编辑

                 bos = [select Id ,Status__c ,Contract__c ,Opportunities__c,Policy__c,FromOpp__c from BloodSugarOrder__c where Id=:backId];
                if(bos.Status__c == '审批中' || bos.Status__c =='审批成功' )setErr('血糖仪配送申请'+bos.Status__c+ ',不能修改!');
                oppId = bos.Opportunities__c;
                try {
                    con = [select Id ,Opportunity__c,Account__c,Account__r.Name  from Contract__c where Id =:bos.Contract__c];
 
                }
                catch (Exception e) {}
                 opp  = [select Id,AccountId,Name ,Account.Name,StageName  from Opportunity  where Id=:oppId];

            }else if( Id.valueOf(backId).getSObjectType() == Opportunity.SObjectType ){//新建
                isNew = true ;
                oppId = backId;
                 opp  = [select Id,AccountId,Name ,Account.Name,StageName  from Opportunity  where Id=:backId];
                if(opp.StageName == '合同签订' || opp.StageName == '失败' )setErr('业务机会'+opp.StageName +'阶段不能操作!');
                bos = new BloodSugarOrder__c();
                bos.Account__c = opp.AccountId ;
                bos.Opportunities__c  = opp.Id;
                bos.FromOpp__c = true; 

            }else if(Id.valueOf(backId).getSObjectType() == Contract__c.SObjectType){//合同发起血糖仪申请

                con = [select Id ,Opportunity__c,Account__c,Account__r.Name ,Status__c from Contract__c where Id =:backId];
                if(con.Status__c != '已生效') setErr('合同未生效不能发起!');
                bos = new BloodSugarOrder__c();
                bos.Account__c = con.Account__c ;

               // bos.Opportunities__c  = opp.Id;
                bos.Contract__c = con.Id;
                bos.FromOpp__c = false; 


            }else{
                setErr('页面打开错误');
            }

            isFromOpp = bos.FromOpp__c;

              Map<String,Object>dataMap = new Map<String,Object>();
             //字段
             Map<String,Set<String>> fieldsmap = getFields();
             //字段详情
             Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
            
            //字段赋值
             Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
            

                 for (DataUtil.FieldBean fb   :  fields.get('BloodSugarOrder__c')) {
                    Map<String,Object> vMap  = new Map<String,Object>();
                    if(fb.name == 'Account__c'){

                        vMap.put('Id', bos.FromOpp__c == true ? opp.Account.Id : con.Account__c );
                        vMap.put('Name', bos.FromOpp__c == true ? opp.Account.Name : con.Account__r.Name );
                        fb.value = vMap;
                    }
                    if( bos.FromOpp__c == true && fb.name == 'Opportunities__c'){

                        vMap.put('Id', opp.Id );
                        vMap.put('Name', opp.Name );
                        fb.value = vMap;
                    }
                 

                 }

             

            
           

            dataMap.put('search',bos.FromOpp__c ?  getDetailFromIntent() : getDetailFromProduct() );
            dataMap.put('detail',getDetails());
            dataMap.put('base',fields);
            dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap));

           dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap), 'UTF-8');


        }catch (Exception e) {
            isErr = true;
            ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()+e.getStackTraceString()));
        }
        
    }
     public Map<String,Set<String>>  getFields(){
        Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
        
            DataUtil.SObjectBean sb = new DataUtil.SObjectBean();

            sb.title ='';
            sb.objname = 'BloodSugarOrder__c';
            sb.stype = DataUtil.getSObjectType('BloodSugarOrder__c');
            if(!isNew)sb.idvalue = bos.Id;
            sb.type = 'base';
            if(!isNew)sb.condition = ' where Id =\''+bos.Id+'\'';
            stageObjectMap.put('BloodSugarOrder__c',sb );
            Set<String>  fields = new Set<String>{'Account__c','Opportunities__c','Company__c','Policy__c','Reason__c'};
            if(bos.FromOpp__c != true) fields.remove('Opportunities__c');
           // if(bos.FromOpp__c != true) fields.add('Contract__c');
            fieldsMap.put('BloodSugarOrder__c', fields);
        
        return fieldsMap;
    }

    public List<BloodBean> getDetailFromIntent(){

        List<BloodBean> tmp = new List<BloodBean> ();
        Map<String ,Product__c> regentMap = new Map<String ,Product__c>();
        for (Product__c p  : [select Id ,Name , Zl__c,Nccode__c from Product__c where Nccode__c in: productMap.values() ] ) {
            regentMap.put(p.Nccode__c, p);
        }
        for ( IntentProduct__c ip : [select Id,Product__r.NCCode__c, Product__r.Name,Product__r.zl__c ,Product__c 
            from  IntentProduct__c where Opportunity__c =:bos.Opportunities__c and Product__r.NCCode__c in: productMap.keySet()  ]) {
        
            tmp.add(new BloodBean(ip, regentMap.get( productMap.get( ip.Product__r.NCCode__c))));
        }
        return tmp; 

    }

    public List<BloodBean> getDetailFromProduct(){

        List<BloodBean> tmp = new List<BloodBean> ();
        Map<String ,Product__c> regentMap = new Map<String ,Product__c>();
        for (Product__c p  : [select Id ,Name , Zl__c,Nccode__c from Product__c where Nccode__c in: productMap.values() ] ) {
            regentMap.put(p.Nccode__c, p);
        }
        for ( Product__c ip : [select Id,NCCode__c, Name,zl__c   
            from  Product__c where  NCCode__c in: productMap.keySet()  ]) {
        
            tmp.add(new BloodBean(ip, regentMap.get( productMap.get( ip.NCCode__c))));
        }
        return tmp; 
    }
    public List<BloodBean> getDetails(){
        List<BloodBean> tmp = new List<BloodBean>();
        if(!isNew){

            for(BloodSugarOrderDetail__c bor : [select Id,DistributionProduct__c, DistributionProduct__r.Name ,
                Product__c,Product__r.Name,Product__r.zl__c , CountT__c,OrderNumber__c,DistributionProductNumber__c,DistributionMax__c 
             from BloodSugarOrderDetail__c where BloodSugarOrder__c =: backId]){

                tmp.add(new BloodBean(bor));

            }
        }
        return tmp;
    }

    public void save(){

        msg = '';
        Map<String,Object> saveMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));


        Map<String,Set<String>> fieldsMap = getFields();
        Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(BloodSugarOrder__c.SObjecttype,fieldsMap.get('BloodSugarOrder__c'));

        Map<String,Object> borMap = ( Map<String,Object>)saveMap.get('base');
       
        for (String field :  borMap.keySet()) {

            if(borMap.get(field) == null || DataUtil.getStringValue(borMap.get(field)) == '') continue;

            bos.put(field, DataUtil.dataHandler(borMap.get(field),fbeanMap.get(field).type.toUpperCase() ));

        }
        List<Object> details = ( List<Object>)saveMap.get('datas'); 
        List<BloodSugarOrderDetail__c> bdList  = new List<BloodSugarOrderDetail__c>();
        Set<String> exsets = new Set<String>();
        for (Object o  : details) {
            Map<String,Object> mo = (Map<String,Object>)o ; 
            BloodSugarOrderDetail__c bd = new BloodSugarOrderDetail__c();
            bd.Id = DataUtil.getStringValue(mo.get('id'));
            bd.DistributionProduct__c = DataUtil.getStringValue(mo.get('eId'));
            bd.Product__c = DataUtil.getStringValue(mo.get('regentId'));
            bd.OrderNumber__c = DataUtil.getDecimalValue(mo.get('pnum'));
            bd.DistributionProductNumber__c = DataUtil.getDecimalValue(mo.get('eno'));
            if(bd.Id != null) exsets.add(bd.Id);
            bdList.add(bd);
            

        }
        SavePoint sp = Database.setSavepoint();

        try {

            if(bos.Id != null)delete [select Id from BloodSugarOrderDetail__c where Id not in: exsets and BloodSugarOrder__c=: bos.Id  ];
            upsert bos ; 
            
            for ( BloodSugarOrderDetail__c bd :bdList ) {
                if(bd.Id == null ) bd.BloodSugarOrder__c = bos.Id;  
            }
            if(bdList.size() > 0 )upsert bdList;
        
            
            msg = '保存成功!';
            isSuccess = true;
            backId = bos.Id;
        }
        catch (Exception e) {
            Database.rollback(sp);
            if(isNew) bos.Id = null;
            msg = '保存失败:'+e.getMessage();
        }
        
            
  

    }
    public class BloodBean{

        public String name ; 
        public String eId;
        public Decimal eno; 
        public Decimal pnum ; 
        public String id ; 
        public String regentId; 
        public String regentName ; 
        public Decimal regentCount;
        public Decimal maxeNum;
        public Decimal zl ;

        public BloodBean (BloodSugarOrderDetail__c bsd ){

            name = bsd.DistributionProduct__r.Name ; 
           eId = bsd.DistributionProduct__c;
            eno = bsd.DistributionProductNumber__c;

            pnum = bsd.OrderNumber__c;
            id = bsd.Id;
            regentId = bsd.Product__c ; 
            regentName = bsd.Product__r.Name;

            regentCount = bsd.CountT__c;
            maxeNum = bsd.DistributionMax__c;
            zl = Decimal.valueOf(bsd.Product__r.zl__c);

        }

        public BloodBean (Product__c bsd,Product__c p  ){

            name = bsd.Name ; 
            eId = bsd.Id   ;

            if(p != null )regentId = p.Id  ; 
            if(p != null )regentName = p.Name ;

            if(p!= null )zl = Decimal.valueOf(p.zl__c);

        }

        public BloodBean (IntentProduct__c bsd,Product__c p  ){

            name = bsd.Product__r.Name ; 
            eId = bsd.Product__c  ;

            if(p != null )regentId = p.Id  ; 
            if(p != null )regentName = p.Name ;

            if(p!= null )zl = Decimal.valueOf(p.zl__c);

        }

    }



}